package br.com.serialmanager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import br.com.serialmanager.model.bean.Mascara;
import br.com.serialmanager.model.dao.MascaraDao;
import br.com.serialmanager.model.dao.SoftwareDao;

public class NovaMascaraActivity extends Activity implements OnItemClickListener, OnClickListener {

	private EditText formato;
	private MascaraDao mascaraDao;
	private SoftwareDao softwareDao;
	private ListView listagemMascaras;
	private List<String> mascaras;
	private AlertDialog dialogOpcoes;
	private AlertDialog dialogConfirmacao;
	private int itemSelecionado;
	private ArrayAdapter<String> adapter;
	private String idMascara;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.nova_mascara);
		
		this.softwareDao = new SoftwareDao(this);
		this.mascaraDao = new MascaraDao(this);
		this.mascaras = this.getListaMascaras();
		
		this.formato = (EditText) this.findViewById(R.id.formatoDaMascara);
		this.listagemMascaras = (ListView) this.findViewById(R.id.listagemMascaras);
		
		this.dialogOpcoes = this.criarDialogOpcoes();
		this.dialogConfirmacao = this.criarDialogConfirmacao();
	}
	
	private AlertDialog criarDialogConfirmacao() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.mensagem_confirmacao_excluir));
		builder.setPositiveButton(R.string.sim, this);
		builder.setNegativeButton(R.string.nao, this);
		return builder.create();
	}

	private AlertDialog criarDialogOpcoes() {
		// TODO Auto-generated method stub
		final CharSequence[] items = {
				getString(R.string.editar),
				getString(R.string.remover),
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.opcoes));
		builder.setItems(items, this);
		return builder.create();
	}

	private List<String> getListaMascaras() {
		List<Map<String, Object>> mascaras = this.mascaraDao.listarMascaras();
		List<String> itensLista = new ArrayList<String>();
		if (!mascaras.isEmpty()) {
			for (Map<String, Object> map : mascaras) {
				itensLista.add(map.get("masc_formato").toString());
			}
		}
		return itensLista;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		this.adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.mascaras);
		this.listagemMascaras.setAdapter(this.adapter);
		this.listagemMascaras.setOnItemClickListener(this);
	}
	
	public void salvarMascara(View view) {
		if (this.validarCampos()) {
			String formatoAntigo = null;
			Integer id = null;
			if (this.idMascara != null) {
				id = Integer.valueOf(this.idMascara);
				formatoAntigo = this.mascaraDao.carregarPorId(this.idMascara).getFormato();
				int indexItem = this.mascaras.indexOf(formatoAntigo);
				this.mascaras.remove(indexItem);
			}
			Mascara mascara = new Mascara(id, this.formato.getText().toString());
			if (this.mascaraDao.salvarMascara(mascara)) {
				Toast.makeText(this, R.string.registro_salvo, Toast.LENGTH_SHORT).show();
				this.mascaras.add(mascara.getFormato());
				this.listagemMascaras.invalidateViews();
				this.formato.setText("");
				return;
			}
		}
		Toast.makeText(this, R.string.erro_salvar, Toast.LENGTH_SHORT).show();
	}
	
	private boolean validarCampos() {
		boolean resultado = false;
		String formato = this.formato.getText().toString();
		if (formato.trim().length() > 0) {
			Mascara mascara = this.mascaraDao.carregarPorFormato(formato);
			if (mascara == null) {
				resultado = true;
			}
		}
		return resultado;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		this.itemSelecionado = position;
		this.dialogOpcoes.show();
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		switch (which) {
			case 0:
				Mascara mascara = this.mascaraDao.carregarPorFormato(this.mascaras.get(this.itemSelecionado));
				this.idMascara = String.valueOf(mascara.getId());
				this.formato.setText(mascara.getFormato());
				break;
			case 1:
				this.dialogConfirmacao.show();
				break;
			case DialogInterface.BUTTON_POSITIVE:
				Mascara masc = this.mascaraDao.carregarPorFormato(this.mascaras.get(this.itemSelecionado));
				this.apagarMascara(masc);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				this.dialogConfirmacao.dismiss();
				break;
		}
	}
	
	private void apagarMascara(Mascara mascara) {
		int softwaresPorMascara = this.softwareDao.listarSoftwaresPorMascara(String.valueOf(mascara.getId())).size();
		if (softwaresPorMascara > 0) {
			Toast.makeText(this, R.string.existem_softwares_com_essa_mascara, Toast.LENGTH_SHORT).show();
			return;
		} else {
			this.mascaraDao.apagarMascara(String.valueOf(mascara.getId()));
			this.mascaras.remove(this.itemSelecionado);
			this.listagemMascaras.invalidateViews();
		}
	}
}
